<?php
// 应用公共文件
/**
 * 产生随机数字
 *
 * @param $length
 * @param string $chars
 * @return string
 */
function random($length, $chars = '0123456789')
{
    $hash = '';
    $max = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

/**
 * 生成随机字符串
 * @param int $lenth
 * @return mixed
 */
function createRandomStr($lenth = 8)
{
    return random($lenth, '123456789abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ');
}

/**
 * 对用户的密码进行加密
 * @param $password
 * @param string $encrypt
 * @return array|string
 */
function password($password, $encrypt = '')
{
    $pwd = [];
    $pwd['salt'] = $encrypt ? $encrypt : createRandomStr();
    $pwd['password'] = md5(md5(trim($password)) . $pwd['salt']);
    return $encrypt ? $pwd['password'] : $pwd;
}

/**
 * 成功返回
 * @param string $msg
 * @param array $data
 * @param int $code
 * @return array
 */
function _S($msg = '', $data = [], $code = 0)
{
    return ['flag' => true, 'msg' => $msg, 'data' => $data, 'code' => $code];
}

/**
 * 错误返回
 * @param string $msg
 * @param array $data
 * @param int $code
 * @return array
 */
function _E($msg = '', $data = [], $code = 1)
{
    return ['flag' => false, 'msg' => $msg, 'data' => $data, 'code' => $code];
}

/**
 * 递归tree
 * @param $data
 * @param int $parentId
 * @return array
 */
function findTree($data, $parentId = 0)
{
    $newData = [];
    foreach ($data as $key => $value) {
        if ($value['parent_id'] == $parentId) {
            $value['list'] = findTree($data, $value['id']);
            $newData[] = $value;
        }
    }
    return $newData;
}

/**
 * 获取客户端IP地址
 * @param integer $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
 * @param boolean $adv 是否进行高级模式获取（有可能被伪装）
 * @return mixed
 */
function getClientIp($type = 0, $adv = false)
{
    $type = $type ? 1 : 0;
    static $ip = NULL;
    if ($ip !== NULL) {
        return $ip[$type];
    }

    if ($adv) {
        if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            $pos = array_search('unknown', $arr);
            if (false !== $pos) {
                unset($arr[$pos]);
            }

            $ip = trim($arr[0]);
        } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
            $ip = $_SERVER['HTTP_CLIENT_IP'];
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
    } elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    // IP地址合法验证
    $long = sprintf("%u", ip2long($ip));
    $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
    return $ip[$type];
}

/**
 * 返回int类型的IP地址
 * @return float|int
 */
function getClientIpLong()
{
    $ip = getClientIp();
    return bindec(decbin(ip2long($ip)));
}

/**
 * 获取游览器标识
 * @return string
 */
function getUserBrowser()
{
    if (empty($_SERVER['HTTP_USER_AGENT'])) {
        return '';
    }
    $agent = $_SERVER['HTTP_USER_AGENT'];
    $browser = '';
    $browser_ver = '';
    if (preg_match('/MSIE\s([^\s|;]+)/i', $agent, $regs)) {
        $browser = 'Internet Explorer';
        $browser_ver = $regs[1];
    } elseif (preg_match('/FireFox\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'FireFox';
        $browser_ver = $regs[1];
    } elseif (preg_match('/Maxthon/i', $agent, $regs)) {
        $browser = '(Internet Explorer ' . $browser_ver . ') Maxthon';
        $browser_ver = '';
    } elseif (preg_match('/Opera[\s|\/]([^\s]+)/i', $agent, $regs)) {
        $browser = 'Opera';
        $browser_ver = $regs[1];
    } elseif (preg_match('/OmniWeb\/(v*)([^\s|;]+)/i', $agent, $regs)) {
        $browser = 'OmniWeb';
        $browser_ver = $regs[2];
    } elseif (preg_match('/Netscape([\d]*)\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Netscape';
        $browser_ver = $regs[2];
    } elseif (preg_match('/safari\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Safari';
        $browser_ver = $regs[1];
    } elseif (preg_match('/NetCaptor\s([^\s|;]+)/i', $agent, $regs)) {
        $browser = '(Internet Explorer ' . $browser_ver . ') NetCaptor';
        $browser_ver = $regs[1];
    } elseif (preg_match('/Lynx\/([^\s]+)/i', $agent, $regs)) {
        $browser = 'Lynx';
        $browser_ver = $regs[1];
    }
    if (!empty($browser)) {
        return addslashes($browser . ' ' . $browser_ver);
    } else {
        return 'Unknow browser';
    }
}

/**
 * 计算小数点后位数
 * @param $num
 * @return int
 */
function getFloatLength($num)
{
    $count = 0;

    $temp = explode('.', $num);

    if (sizeof($temp) > 1) {
        $decimal = end($temp);
        $count = strlen($decimal);
    }

    return $count;
}

/**
 * 数据风控
 * @param $price
 * @param $product
 * @return float|int
 */
function fengkong($price, $product)
{
    $pointLow = $product['point_low'];
    $pointTop = $product['point_top'];

    $floatLength = getFloatLength($pointTop);

    $jishuRand = pow(10, $floatLength);

    $pointLow = $pointLow * $jishuRand;
    $pointTop = $pointTop * $jishuRand;

    $rand = rand((int)$pointLow, (int)$pointTop) / $jishuRand;

    $_new_rand = rand(0, 10);
    if ($_new_rand % 2 == 0) {
        $price = $price + $rand;
    } else {
        $price = $price - $rand;
    }

    return $price;
}

/**
 * 随机数
 * @param $maxValue
 * @return int
 */
function randNum($maxValue)
{
    if (is_int($maxValue)) {
        $randomValue = rand(0, $maxValue);
    } else {
        //小数直接返回0
        $randomValue = 0;
    }

    return $randomValue;
}

/**
 * Get远程请求
 * @param $url
 * @return void
 */
function curlGet($url)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用对等证书的验证
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); // 禁用主机名验证
    $response = curl_exec($ch);

    // 检查是否有错误
    if(curl_errno($ch)) {
        return _E('Error:' . curl_error($ch));
    }

    $result = json_decode($response, true);

    return _S('获取成功',$result);

    curl_close($ch);
}

